package cn.stylefeng.guns.modular.fsjs.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.stylefeng.roses.core.base.controller.BaseController;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;

import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ServerResponse;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.stylefeng.guns.modular.system.model.Basemsg;
import cn.stylefeng.guns.modular.system.model.Bindclient;
import cn.stylefeng.guns.modular.system.model.Midwater;
import cn.stylefeng.guns.modular.system.model.Swyreport;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.fsjs.service.ISwyreportService;

/**
 * 节约用水年报控制器
 *
 * @author fengshuonan
 * @Date 2019-03-06 18:45:04
 */
@Controller
@RequestMapping("/swyreport")
public class SwyreportController extends BaseController {

    private String PREFIX = "/fsjs/swyreport/";

    @Autowired
    private ISwyreportService swyreportService;
    @Autowired
    private IUserService userService;

    /**
     * 跳转到节约用水年报首页
     */
    @RequestMapping("")
    public String index(HttpServletRequest request) {
    	User user=userService.selectById(ShiroKit.getUser().getId());
    	request.setAttribute("Operater", user.getName());
    	request.setAttribute("phone", user.getPhone());
    	SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
    	request.setAttribute("Ts", sf.format(new Date()));
        return PREFIX + "swyreport.html";
    }

    /**
     * 跳转到添加节约用水年报
     */
    @RequestMapping("/swyreport_add")
    public String swyreportAdd() {
        return PREFIX + "swyreport_add.html";
    }

    /**
     * 跳转到修改节约用水年报
     */
    @RequestMapping("/swyreport_update/{swyreportId}")
    public String swyreportUpdate(@PathVariable Integer swyreportId, Model model) {
        Swyreport swyreport = swyreportService.selectById(swyreportId);
        model.addAttribute("item",swyreport);
        LogObjectHolder.me().set(swyreport);
        return PREFIX + "swyreport_edit.html";
    }

    /**
     * 获取节约用水年报列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return swyreportService.selectList(null);
    }

    /**
     * 新增节约用水年报
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Swyreport swyreport) {
        swyreportService.insert(swyreport);
        return SUCCESS_TIP;
    }

    /**
     * 删除节约用水年报
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer swyreportId) {
        swyreportService.deleteById(swyreportId);
        return SUCCESS_TIP;
    }

    /**
     * 修改节约用水年报
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Swyreport swyreport) {
        swyreportService.updateById(swyreport);
        return SUCCESS_TIP;
    }

    /**
     * 节约用水年报详情
     */
    @RequestMapping(value = "/detail/{swyreportId}")
    @ResponseBody
    public Object detail(@PathVariable("swyreportId") Integer swyreportId) {
        return swyreportService.selectById(swyreportId);
    }
    
    @RequestMapping(value = "/pushMsg")
    @ResponseBody
    public Object pushMsg(String json,HttpServletRequest request) {
    	List<Swyreport> swyreportLi = JSON.parseArray(json,
    			Swyreport.class);
//    	basemsg.setAccount(userService.selectById(ShiroKit.getUser().getId()).getAccount());
//    	basemsg.setIssubmit("1");
//    	basemsg.setOperater("456");
//    	basemsg.setTs("2019-03-07");
//    	basemsg.setVersion("2");
//    	System.out.println("正常提取数据");
//    	System.out.println(JSONObject.toJSONString(basemsg));
    	return swyreportService.pushMsg(request,swyreportLi);
    }
    @RequestMapping(value = "/showPDF")
    @ResponseBody
    public Object showPDF(HttpServletRequest request,HttpServletResponse  response ) throws Exception {
    	Integer id = ShiroKit.getUser().getId(); 
    	User user = userService.selectById(id);
//    	List<Basemsg> tmp=basemsgService.getMsgByAccount(user);
//    	ExcellUtil.copyFile(request, tmp.get(0),"用水单位基本信息");
//    	ExcellUtil.excel2Pdf(request, tmp.get(0),"用水单位基本信息");
    	response.setContentType("application/pdf");
    	System.out.println(request.getSession().getServletContext().getRealPath("/"));
//    	String path=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\模板.pdf";
    	//"E:/接口开发/佛山市节水统计问券调查/测试excell转pdf/test/模板.pdf"
    	String file3=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\"+user.getAccount()+"_节水量年报.pdf";
    	File file=new File(file3);
    	if(!file.exists()){
    		Swyreport swyreport =new Swyreport();
    		swyreport.setRecYear(Calendar.getInstance().get(Calendar.YEAR));
    		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
    		swyreport.setTs(sf.format(new Date()));
    		swyreport.setAccount(user.getAccount());
    		swyreport.setOperater(user.getName());
    		swyreportService.bulidEmptyFile(request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\",swyreport, user);
//    		return ServerResponse.createByErrorMessage("数据未填写保存");
    	}
    	FileInputStream in = new FileInputStream(new File(file3));
    	OutputStream out = response.getOutputStream();
    	byte[] b = new byte[512];
    	while ((in.read(b))!=-1) {
    	out.write(b);
    	}
    	out.flush();
    	in.close();
    	out.close();
    	return null;
    }
    
    
    @RequestMapping(value = "/dlExcell")
    public Object dlExcell(HttpServletRequest request,HttpServletResponse  response ) throws Exception {
    	Integer id = ShiroKit.getUser().getId(); 
    	User user = userService.selectById(id);
    	String name=user.getAccount()+"_节水量年报.xlsx";
    	String file3=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\"+name;
    	File file=new File(file3);
    	if(!file.exists()){
    		Swyreport swyreport =new Swyreport();
    		swyreport.setRecYear(Calendar.getInstance().get(Calendar.YEAR));
    		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
    		swyreport.setTs(sf.format(new Date()));
    		swyreport.setAccount(user.getAccount());
    		swyreport.setOperater(user.getName());
    		swyreportService.bulidEmptyFile(request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\",swyreport, user);
//    		return ServerResponse.createByErrorMessage("数据未填写保存");
    	}
    	String fileName = new String(name.getBytes(),"ISO8859-1");
    	request.setCharacterEncoding("UTF-8");
        //第一步：设置响应类型
        response.setContentType("application/force-download");//应用程序强制下载
        //第二读取文件
        InputStream in = new FileInputStream(file);
        //设置响应头，对文件进行url编码
//        name = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);   
        response.setContentLength(in.available());
        
        //第三步：开始copy
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
          out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        return null;
    }
    
    @RequestMapping(value = "/dlEmpExcell")
    public Object dlEmpExcell(HttpServletRequest request,HttpServletResponse  response ) throws Exception {
    	String name="节水量年报.xlsx";
    	String file3=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\"+name;
    	File file=new File(file3);
    	String fileName = new String(name.getBytes(),"ISO8859-1");
    	request.setCharacterEncoding("UTF-8");
        //第一步：设置响应类型
        response.setContentType("application/force-download");//应用程序强制下载
        //第二读取文件
        InputStream in = new FileInputStream(file);
        //设置响应头，对文件进行url编码
//        name = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);   
        response.setContentLength(in.available());
        
        //第三步：开始copy
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
          out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        return null;
    }
    
    @RequestMapping(value = "/getTemp")
    @ResponseBody
    public Object getDanweiMain(HttpServletRequest request,HttpServletResponse  response ) throws Exception {
    	Integer id = ShiroKit.getUser().getId(); 
    	User user = userService.selectById(id);
    	List<Swyreport> tmp=swyreportService.getMsgByAccount(user);
    	if(tmp.size()>0){
    		return tmp;
    	}else{
    		return null;
    	}
    }
    
  //处理文件上传
    @RequestMapping(value="/uploadFile", method = RequestMethod.POST)
    public @ResponseBody Object uploadImg(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
    	if (file.isEmpty()) {
            return ServerResponse.createByErrorMessage("上传失败，请选择文件");
        }
    	Integer id = ShiroKit.getUser().getId(); 
    	User user = userService.selectById(id);
    	if(swyreportService.getIfComit(user)==0){
			return ServerResponse.createByErrorMessage("年报数据未提交，无法上传文件");
		}
    	String contentType = file.getContentType();
    	//image/jpeg   application/pdf
        if("image/jpeg".equals(contentType)||"application/pdf".equals(contentType)){
        	/*Integer id = ShiroKit.getUser().getId(); 
        	User user = userService.selectById(id);*/
        	String name="";
        	String filePath = request.getSession().getServletContext().getRealPath("/")+"\\static\\uploadFile\\";
        	
        	if("image/jpeg".equals(contentType)){
        		name=user.getAccount()+"_节水量年报_upload.jpg";
        		File tempFile=new File(filePath+name);
        		if(tempFile.exists()){
                	return ServerResponse.createByErrorMessage("已经上传过该文件");
                }
        	}else{
        		name=user.getAccount()+"_节水量年报_upload.pdf";
        		File tempFile=new File(filePath+name);
        		if(tempFile.exists()){
                	return ServerResponse.createByErrorMessage("已经上传过该文件");
                }
        	}
        	File dest = new File(filePath + name);
        	try {
        		file.transferTo(dest);
        		return ServerResponse.createBySuccessMessage("上传成功");
        	} catch (IOException e) {
        		return ServerResponse.createByErrorMessage("未知错误，请联系管理员");
        	}
        }else{
        	return  ServerResponse.createByErrorMessage("不允许上传该格式文件");
        }
    }
}
